import React, { useEffect, useState } from 'react';
import { Button, Card, Form, Input, Select, Space, message } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import MyTable from '../../components/MyTable';
import { getBoxTypeList, deleteBoxType } from '../../api/boxType';
import BoxTypeDialog from './BoxTypeDialog';
import '../../assets/css/boxType.scss';

const { Option } = Select;

const BoxType: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<any[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });
  const [visible, setVisible] = useState(false);
  const [currentBoxType, setCurrentBoxType] = useState<any>(null);

  // 获取箱子类型列表
  const fetchBoxTypeList = async (params: any = {}) => {
    setLoading(true);
    try {
      const { current, pageSize, ...restParams } = params;
      const res = await getBoxTypeList({
        pageIndex: current || pagination.current,
        pageSize: pageSize || pagination.pageSize,
        ...restParams
      });
      console.log(res);
      
      if (res && res.code === 200) {
        // 根据实际返回的数据结构调整
        setTableData(res.data.data || []);
        setPagination({
          ...pagination,
          current: params.current || pagination.current,
          pageSize: params.pageSize || pagination.pageSize,
          total: res.data.totalCount || 0
        });
      }
    } catch (error) {
      console.error('获取箱子类型列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchBoxTypeList();
  }, []);

  // 表格列配置
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) => {
        return (pagination.current - 1) * pagination.pageSize + index + 1;
      }
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '长(CM)',
      dataIndex: 'length',
      key: 'length'
    },
    {
      title: '宽(CM)',
      dataIndex: 'width',
      key: 'width'
    },
    {
      title: '高(CM)',
      dataIndex: 'height',
      key: 'height'
    },
    {
      title: '备注',
      dataIndex: 'notes',
      key: 'notes'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <span className={`status ${status === 1 ? 'active' : 'inactive'}`}>
          {status === 1 ? '启用' : '禁用'}
        </span>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: any) => (
        <Space size="middle">
          <Button 
            type="primary" 
            size="small" 
            onClick={() => handleEdit(record)}
          >
            修改
          </Button>
          <Button 
            type="primary" 
            danger 
            size="small" 
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  // 搜索
  const handleSearch = () => {
    const values = form.getFieldsValue();
    fetchBoxTypeList({
      current: 1,
      ...values
    });
  };

  // 重置
  const handleReset = () => {
    form.resetFields();
    fetchBoxTypeList({
      current: 1
    });
  };

  // 表格变化
  const handleTableChange = (page: any) => {
    const { current, pageSize } = page;
    setPagination({ ...pagination, current, pageSize });
    fetchBoxTypeList({
      current,
      pageSize,
      ...form.getFieldsValue()
    });
  };

  // 添加箱子类型
  const handleAdd = () => {
    setCurrentBoxType(null);
    setVisible(true);
  };

  // 编辑箱子类型
  const handleEdit = (record: any) => {
    setCurrentBoxType(record);
    setVisible(true);
  };

  // 删除箱子类型
  const handleDelete = async (id: number) => {
    try {
      const res = await deleteBoxType(id);
      if (res && res.code === 200) {
        message.success('删除成功');
        fetchBoxTypeList({
          ...pagination,
          ...form.getFieldsValue()
        });
      } else {
        message.error(res?.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除箱子类型失败:', error);
      message.error('删除失败');
    }
  };

  // 对话框确认
  const handleDialogConfirm = () => {
    setVisible(false);
    fetchBoxTypeList({
      ...pagination,
      ...form.getFieldsValue()
    });
  };

  return (
    <div className="box-type-container">
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: '20px' }}
        >
          <Form.Item name="name" label="名称">
            <Input placeholder="请输入名称" allowClear />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 120 }}>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset}>重置</Button>
          </Form.Item>
          <Form.Item>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={handleAdd}
            >
              添加
            </Button>
          </Form.Item>
        </Form>

        <MyTable
          columns={columns}
          dataSource={tableData}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Card>

      {/* 添加/编辑对话框 */}
      <BoxTypeDialog
        visible={visible}
        boxType={currentBoxType}
        onCancel={() => setVisible(false)}
        onConfirm={handleDialogConfirm}
      />
    </div>
  );
};

export default BoxType; 